package io.kiki.stack.netty.lifeCycle;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Setter
@Getter
public abstract class AbstractLifeCycle implements LifeCycle {

    private final AtomicBoolean inited = new AtomicBoolean(false);

    @Override
    public void startup() throws LifeCycleException {
        if (inited.compareAndSet(false, true)) {
            return;
        }
        throw new LifeCycleException("this component has started");
    }

    @Override
    public void shutdown() throws LifeCycleException {
        if (inited.compareAndSet(true, false)) {
            return;
        }
        throw new LifeCycleException("this component has closed");
    }

    @Override
    public boolean isInited() {
        return inited.get();
    }

    protected void ensureStarted() {
        if (!isInited()) {
            throw new LifeCycleException(String.format("Component(%s) has not been started yet, please startup first!", getClass().getSimpleName()));
        }
    }
}
